<template>
    <div>
        <vxe-toolbar>
            <template #buttons>
                <div class="toolbar-buttons">
                    <el-button @click="openNewExpertDialog" @expertCreated="fetchExperts">新增专家</el-button>
                    <el-input v-model="searchQuery" style="width: 500px;" placeholder="输入【姓名、单位名称、目前从事专业】搜索"
                        @change="filterExperts" />
                    <el-button @click="fetchExperts">查询</el-button>
                </div>
            </template>
        </vxe-toolbar>
        <!--
        <vxe-grid border show-header :data="filteredExperts" :columns="columns" @cell-edit-change="editExpert" :edit-config="{ trigger: 'dblclick', mode: 'cell' }" @edit-closed="saveData">
        -->
        <vxe-grid border show-header :data="filteredExperts" :columns="columns" @cell-edit-change="editExpert" @edit-closed="saveData">
            <template #action="{ row }">
                <el-button link type="primary" @click="deleteExpert(row.id)">删除</el-button>
                <el-button link type="primary" @click="openModifyExpertDialog(row)">编辑</el-button>
            </template>
        </vxe-grid>
        <NewExpertDialog ref="newExpertDialog" @expertCreated="fetchExperts" />
        <ModifyExpertDialog ref="modifyExpertDialog" @expertModified="fetchExperts" />
    </div>
</template>

<script setup>
import { deleteExpertById, getAllExperts } from '@/alova/api';
import ModifyExpertDialog from '@/components/ModifyExpertDialog.vue';
import NewExpertDialog from '@/components/NewExpertDialog.vue';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import { ref } from 'vue';

const searchQuery = ref('');
const loading = ref(false);
const dialogVisible = ref(false); // 控制弹窗显示
const editForm = ref({}); // 存储正在编辑的数据
const modifyExpertDialog = ref(null);
const newExpertDialog = ref(null);

// 专家数据列表
const expertList = ref([]);

// 表格列定义
const columns = ref([
    { field: 'id', title: '序号', width: 80, editRender: { name: 'input' } },
    { field: 'name', title: '姓名', editor: { type: 'text' }, editRender: { name: 'input' } },
    { field: 'idCardNumber', title: '身份证号', editor: { type: 'text' }, editRender: { name: 'input' } },
    { field: 'title', title: '职称', editor: { type: 'text' }, editRender: { name: 'input' } },
    { field: 'education', title: '最高学历', editor: { type: 'text' }, editRender: { name: 'input' } },
    { field: 'majorStudied', title: '所学专业', editor: { type: 'text' }, editRender: { name: 'input' } ,formatter: ({ cellValue }) => cellValue.name },
    { field: 'currentProfession', title: '目前从事专业', editor: { type: 'text' }, editRender: { name: 'input' },formatter: ({ cellValue }) => cellValue.name },
    { field: 'birthDate', title: '出生年月', editor: { type: 'text' }, editRender: { name: 'input' } },
    { field: 'companyName', title: '单位名称', editor: { type: 'text' }, editRender: { name: 'input' } },
    { field: 'position', title: '职务', editor: { type: 'text' }, editRender: { name: 'input' } },
    { field: 'companyAddress', title: '单位地址', editor: { type: 'text' }, editRender: { name: 'input' } },
    { field: 'phoneNumber', title: '联系电话', editor: { type: 'text' }, editRender: { name: 'input' } },
    { field: 'postalCode', title: '邮政编码', editor: { type: 'text' }, editRender: { name: 'input' } },
    { field: 'mobile', title: '手机', editor: { type: 'text' }, editRender: { name: 'input' } },
    { field: 'email', title: '电子邮箱', editor: { type: 'text' }, editRender: { name: 'input' } },
    { title: '操作', field: 'action', slots: { default: 'action' }, width: 120 }
]);

const filteredExperts = ref([...expertList.value]);

const openModifyExpertDialog = (row) => {
    modifyExpertDialog.value.openDialog(row);
};

const openNewExpertDialog = () => {
    newExpertDialog.value.openDialog();
};

const fetchExperts = async () => {
    loading.value = true; // 开始加载
    const loader = ElLoading.service({
        fullscreen: true,
        text: "数据加载中...",
    });
    getAllExperts().then(data => {
        loading.value = false;
        expertList.value = data;
        filteredExperts.value = [...expertList.value];
    }).catch(error => {
        console.error("查询用户失败:", error);
    }).finally(() => {
        loading.value = false; // 结束加载
        loader.close(); // 关闭加载动画
    });
}

fetchExperts();

// 打开弹窗进行编辑
const openEditDialog = (row) => {
    editForm.value = { ...row }; // 复制数据，防止直接修改表格数据
    dialogVisible.value = true;
};

// 保存编辑数据
const saveExpert = () => {
    const index = expertList.value.findIndex(e => e.id === editForm.value.id);
    if (index !== -1) {
        expertList.value[index] = { ...editForm.value };
    }
    dialogVisible.value = false;
};

const saveData = ({ row, field }) => {
    console.log(`字段 ${field} 修改为：`, row[field]);
    // 这里可以调用后端 API 进行数据保存
};

// 编辑专家信息
const editExpert = ({ row, field, value }) => {
    row[field] = value;
};

// 删除专家
const deleteExpert = (id) => {
    ElMessageBox.confirm(
        '此操作将永久删除该专家，是否继续？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        deleteExpertById(id).then(() => {
            ElMessage.success('删除成功！');
            // fetchUsers();
            expertList.value = expertList.value.filter(expert => expert.id !== id);
            filteredExperts.value = [...expertList.value];
        }).catch(error => {
            console.log("删除专家失败:", error);
        }).finally(() => {
            console.log("finally");
        });
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};

// 查询专家
const filterExperts = () => {
    if (!searchQuery.value) {
        filteredExperts.value = [...expertList.value];
    } else {
        filteredExperts.value = expertList.value.filter(expert =>
            expert.name&&expert.name.includes(searchQuery.value)||expert.companyName&&expert.companyName.includes(searchQuery.value)||expert.currentProfession&&expert.currentProfession.name.includes(searchQuery.value)
        );
    }
};
</script>


<style scoped>
.toolbar-buttons {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>